import 'dart:io';
import 'package:flutter/material.dart';
import 'package:ideology/features/screens/widgets/editor_menu_bar/setting/right/download_tab/selected_release_details.dart';
import 'package:ideology/features/screens/widgets/editor_menu_bar/setting/sdk_settings_controller.dart';

/// 下载页签（右侧）
///
/// 功能：
/// - 选择要下载的 SDK 版本
/// - 选择安装目录
/// - 显示版本详情
/// - 下载 / 安装进度反馈
class DownloadTab extends StatelessWidget {
  const DownloadTab({
    super.key,
    required this.releases,
    required this.selected,
    required this.installDir,
    required this.isDownloading,
    required this.progress,
    required this.error,
    required this.onSelectRelease,
    required this.onPickInstallDir,
    required this.onDownload,
  });

  /// 所有可供下载的 SDK 版本
  final List<SdkRelease> releases;

  /// 当前选中的 SDK 版本
  final SdkRelease? selected;

  /// 用户选择的安装目录
  final Directory? installDir;

  /// 是否处于下载中
  final bool isDownloading;

  /// 下载进度（0~1，小于等于 0 表示 indeterminate）
  final double progress;

  /// 错误信息（如果有）
  final String? error;

  /// 切换选中 SDK 版本
  final ValueChanged<SdkRelease> onSelectRelease;

  /// 打开目录选择器
  final VoidCallback onPickInstallDir;

  /// 执行下载
  final VoidCallback onDownload;

  @override
  Widget build(BuildContext context) {
    final cs = Theme.of(context).colorScheme;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        // ---------- 顶部区域：SDK 版本选择 + 安装路径选择 ----------
        Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            /// SDK 版本选择下拉框
            DropdownButtonFormField<SdkRelease>(
              value: selected,
              isExpanded: true,
              items: releases
                  .map(
                    (r) => DropdownMenuItem(
                  value: r,
                  child: Text(
                    r.fileNameWithoutExt,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              )
                  .toList(),
              onChanged: (v) {
                if (v != null) onSelectRelease(v);
              },
              hint: const Text('Select SDK version'),
              decoration: InputDecoration(
                isDense: true,
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(6),
                  borderSide: const BorderSide(color: Colors.grey, width: 1),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(6),
                  borderSide: const BorderSide(color: Colors.grey, width: 1),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(6),
                  borderSide: BorderSide(
                    color: Theme.of(context).colorScheme.primary,
                    width: 2,
                  ),
                ),
              ),
            ),
            const SizedBox(height: 12),

            /// 安装路径选择区域
            Padding(
              padding: const EdgeInsets.only(left: 1),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Install to',
                    style: Theme.of(context).textTheme.labelSmall,
                  ),
                  const SizedBox(height: 4),

                  // 模拟 Dropdown 一致的边框样式
                  Container(
                    height: 40, // 与上方下拉框高度保持一致
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey, width: 1),
                      borderRadius: BorderRadius.circular(6),
                    ),
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(
                            installDir?.path ?? 'Not selected',
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: Theme.of(context).textTheme.bodyMedium,
                          ),
                        ),
                        const SizedBox(width: 6),

                        /// 选择目录按钮
                        IconButton(
                          tooltip: 'Choose directory',
                          constraints: const BoxConstraints(), // 避免撑高
                          onPressed: onPickInstallDir,
                          icon: const Icon(Icons.folder_open, size: 20),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        const SizedBox(height: 12),

        // ---------- 底部区域：用可滚动区域包裹，防止内容溢出 ----------
        Expanded(
          child: Scrollbar(
            // 带滚动条（可选，美观）
            thumbVisibility: true,
            child: SingleChildScrollView(
              primary: true,
              // 内容较多时可滑动
              child: Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(6),
                  border: Border.all(color: cs.onSurface.withOpacity(0.05)),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    /// 展示所选 SDK 版本的详细信息
                    SelectedReleaseDetails(release: selected),
                    const SizedBox(height: 12),

                    /// 错误提示
                    if (error != null)
                      Text(error!, style: TextStyle(color: cs.error), maxLines: 2),

                    const SizedBox(height: 6),
                    // Spacer() 替换为 SizedBox，避免滚动下拉无法撑满
                    const SizedBox(height: 12),

                    /// 下载按钮 / 下载进度显示
                    if (isDownloading)
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          LinearProgressIndicator(
                            value: progress == 0 ? null : progress,
                          ),
                          const SizedBox(height: 8),
                          Row(
                            children: [
                              Expanded(
                                child: Text(
                                  progress == 0
                                      ? 'Downloading...'
                                      : '${(progress * 100).toStringAsFixed(0)}%',
                                ),
                              ),
                              /// Cancel 功能未在 controller 中实现，这里先禁用
                              TextButton(
                                onPressed: null,
                                child: const Text('Cancel'),
                              ),
                            ],
                          ),
                        ],
                      )
                    else
                      Center(
                        child: ElevatedButton.icon(
                          onPressed: (selected != null && installDir != null)
                              ? onDownload
                              : null,
                          icon: const Icon(Icons.download),
                          label: const Text('Download & Install'),
                        ),
                      ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}
